package com.topisv.tms.web.stock.instorageNew;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.receiptDetail.ReceiptDetail;
import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.entity.stock.instorage.InstorageBill;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.instorageNew.InstorageBillNewService;
import com.topisv.tms.service.stock.instorageNew.InstorageScanService;
import com.topisv.tms.web.base.BaseDataTableController;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 入库(新)_control
 * @author ch
 */
@Controller
@RequestMapping(value = "/v2_instorageBillNew")
public class InstorageBillNewController  extends BaseDataTableController{
	private static final Logger logger = LoggerFactory.getLogger(InstorageBillNewController.class);
	@Autowired
	private InstorageBillNewService instorageBillNewService;
	@Autowired
	private InstorageScanService instorageScanService;
	@Autowired
    private EdiGoodsSkuService ediGoodsSkuService;
	/**
	 * 
	 * 导向入库单列表页面
	 * @param model
	 * @param request
	 * @return 
	 */
	@RequestMapping(value = "v2_toInstorageBillListPage")
	public String toInstorageBillListPage(Model model) {
		try {
			fillSelectValue(model, null);
		} catch (Exception e) {
			log.error("error",e);
		}
		return "instorageNew/instorageBillListNew";
	}
	/**
	 * 查询入库单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryInstorageBill",method=RequestMethod.POST)
	public void queryInstorageBill(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response) {
		try {
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			//查询入库单
			Page<InstorageBill> page = this.instorageBillNewService.loadPageByParam(paramHolder.getSearchParams(),paramHolder.getCurPage(), paramHolder.getPageSize());
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			
			log.error("error",e);
		}
	}
	/**
	 * 扫描收货页面
	 * @param bill
	 * @return
	 */
	@RequestMapping(value = "toInstorageCountPageNew/{billId}",method = RequestMethod.GET)
	public String toInstorageCountPageNew(@PathVariable("billId") Long billId, Model model) {
		try {
			InstorageBill  task=this.instorageBillNewService.loadById(billId);
		    model.addAttribute("task", task);
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			String areagroups=curUser.areagroups;
//			List<Map<String, Object>> lpnList = instorageScanService.getLpnList(areagroups);
//			model.addAttribute("lpnList", lpnList);
			List<Map<String, Object>> result = instorageScanService.getInstorageScanDetail(billId);
			model.addAttribute("items", result);
		} catch (Exception e) {
			log.error("error",e);
			
		}
		return "instorageNew/instorageScan";
	}
	/**
	 * lpn检查
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "lpnCheck",method = RequestMethod.POST)
	public void lpnCheck(ServletRequest request,HttpServletResponse response) {
			JSONObject json = null;
			PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String msg="";
			String lpnNum=request.getParameter("lpnNum");
			String warehouseCode=request.getParameter("warehouseCode");
				//检查LPN有没有被占用
				List<Map<String, Object>> LPNcheck=instorageScanService.checkLPN(lpnNum,warehouseCode);
				if(LPNcheck.size()>0){
					json.put("status","success");
	//				json.put("items", result);
				}else{
					msg="LPN被占用或者LPN跟仓库不对应或者不存在，请检查";
					json.put("status","error");
					json.put("content",msg);
				}
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	
	/**
	 * 确认收货
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "confirmReceive",method = RequestMethod.POST)
	public void confirmReceive(ServletRequest request,HttpServletResponse response) {
			JSONObject json = null;
			PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String msg="";
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			String skus=request.getParameter("skus");
			String lpnNum=request.getParameter("lpnNum");
			String billCode=request.getParameter("billCode");
			Long billId=Long.valueOf(request.getParameter("billId"));
			String errorflag=request.getParameter("errorflag");
			String warehouseCode=request.getParameter("warehouseCode");
			JSONArray jsonArray = JSONArray.fromObject(skus); 
			String tmpNewStatus="";
			if(jsonArray.size()>0){
				//检查LPN有没有被占用
				List<Map<String, Object>> LPNcheck=instorageScanService.checkLPN(lpnNum,warehouseCode);
				if(LPNcheck.size()>0){
					InstorageBill instorageBill = instorageBillNewService.loadBillByCode(billCode); 
					for(int i = 0; i < jsonArray.size(); i++){  
						HashMap<String,Object> param=new HashMap<String,Object>();
						JSONObject object=(JSONObject) jsonArray.get(i);
						String sku=object.getString("sku");
						int num=object.getInt("num");
						String skuName=object.getString("skuname");
						String batchCode = object.getString("batchCode");
						String productDate = object.getString("productDate");
						String expireDate = object.getString("expireDate");
						if("".equals(tmpNewStatus)){
						    tmpNewStatus=instorageBill.getNewstatus();
						}
						//统计该入库单该sku在入库收货明细单中的数量
						List<Map<String, Object>> receiptDetailList=instorageScanService.getReceiptDetailByBillCodeAndSKUNew(billCode,
						    sku,batchCode, productDate, expireDate);
						///该入库单该sku预约入库单明细
						List<Map<String, Object>> billItemPreSKUList=instorageScanService.getBillItemPreByBillCodeAndSKUNew(billCode,
						    sku,batchCode, productDate, expireDate);
						if(billItemPreSKUList.size()>0){
							int billItemPreSKUNum=Integer.valueOf(String.valueOf(billItemPreSKUList.get(0).get("goods_num")));
							int countNum=0;
							if(receiptDetailList.size()>0){
								 countNum=Integer.valueOf(String.valueOf(receiptDetailList.get(0).get("countNum")));
							}
							if(billItemPreSKUNum>=(num+countNum)&&num>0){
									param.put("instorageBill", instorageBill);
									param.put("num", num);
									param.put("batchCode", batchCode);
									param.put("productDate",productDate);
									param.put("expireDate", expireDate);
									param.put("skuName", skuName);
									param.put("lpnNum", lpnNum);
									param.put("sku", sku);
									param.put("errorflag", errorflag);
									this.instorageBillNewService.createNewReceiptDetail(param);
									instorageScanService.updateLPNStatus(String.valueOf(LPNcheck.get(0).get("id")), "1",billCode);
									//根据入库id查询预约入库明细中的sku数量等于收货明细中sku的数量的记录
									List<Map<String, Object>> result=instorageScanService.loadAllReceiptDetailSKUNoNew(billId);
									//该入库单所有预约入库明细的记录
									List<Map<String, Object>> billItemPreList=instorageScanService.getAllBillItemPre(billCode);
									String flag="0";
									//边拣边上架，-1代表不走边收货边上架流程 0：新建 1:部分收货未上架  2:部分收货部分上架 3:部分收货完全上架 4:完全收货未上架 5:完全收货部分上架 6:完全收货完全上架 7:已关闭 8:已取消
									if(result.size()<billItemPreList.size()){//部分收货
										if(tmpNewStatus.equals("0")){//第一次收货
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"1");
											tmpNewStatus="1";
											instorageBillNewService.updateInstorageBillStatus(billCode);
											instorageScanService.updateInstorageBillPreStatus(instorageBill.getAboutCode());
											flag="1";
										}
										if(tmpNewStatus.equals("3")){//部分收货完全上架
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"2");
											tmpNewStatus="2";
											flag="2";
										}
									}else if(result.size()==billItemPreList.size()){//完全收货
										if(tmpNewStatus.equals("0")){//第一次收货
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"4");
											tmpNewStatus="4";
											instorageBillNewService.updateInstorageBillStatus(billCode);
											instorageScanService.updateInstorageBillPreStatus(instorageBill.getAboutCode());
											flag="4";
										}else if(tmpNewStatus.equals("1")){//1:部分收货未上架
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"4");
											tmpNewStatus="4";
											flag="4";
										}else if(tmpNewStatus.equals("2")){//:部分收货部分上架
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"5");
											tmpNewStatus="5";
											flag="5";
										}else if(tmpNewStatus.equals("3")){//3:部分收货完全上架 
											instorageBillNewService.updateInstorageBillNewStatus(billCode,"5");
											tmpNewStatus="5";
											flag="5";
										}
									}
									//收货的入库日志
									instorageBillNewService.saveInstorageLog(instorageBill.getBillCode(),curUser,lpnNum,skuName,num,flag);
									
							}else{
								msg+=sku+"超量了，该预约数量为"+billItemPreSKUNum+",已收货:"+countNum+",扫描:"+num+";";
							}
						}
					}
					json.put("status","success");
					json.put("content",msg);
	//				json.put("items", result);
				}else{
					msg="LPN被占用";
					json.put("status","error");
					json.put("content",msg);
				}
			}else{
					json.put("status","error");
					json.put("content","预约入库单明细为空");
			}
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	/**
	 * 导向入库单明细页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toInstorageBillDetailPage/{billCode}")
	public String toInstorageBillDetailPage(@PathVariable("billCode")String billCode,Model model) {
		try {
			//入库单
			InstorageBill inBill=this.instorageBillNewService.loadBillByCode(billCode);
			model.addAttribute("inBill", inBill);
			//预约明细
			List<Map<String, Object>> preInstorageDetail = instorageScanService.getInstorageScanDetail(inBill.getId());
			model.addAttribute("preInstorageDetail", preInstorageDetail);
			
			//收货明细
			List<Map<String, Object>> receiptDetailList=this.instorageScanService.getReceiptDetailByBillCode(billCode);
			model.addAttribute("receiptDetailList", receiptDetailList);
			
		} catch (Exception e) {
			
			log.error("error",e);
		}
		return "instorageNew/instorageBillDetailNew";
	}
	/**
	 * 打印订单详情
	 * @param billCode
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "printInstorageBillDetail",method=RequestMethod.POST)
	public void printInstorageBillDetail(ServletRequest req,HttpServletResponse rep) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = rep.getWriter();
			String msg="";
			String billCode=req.getParameter("billCode");
			String printType=req.getParameter("printType");
			json.put("status","success");
			if(StringUtils.equals(printType, "1")){//打印验收单
				json.put("instorageBillItemYSList",instorageBillNewService.printInstorageBillDetailForYS(billCode));
				instorageBillNewService.updateInstorageBillPrintYsNum(billCode);
			}else if(StringUtils.equals(printType, "2")){//打印上架单
				json.put("instorageBillItemSJList",instorageBillNewService.printInstorageBillDetailForUp(billCode));
				instorageBillNewService.updateInstorageBillPrintSjNum(billCode);
			}
			json.put("receiptDate",instorageBillNewService.getReceiptDetailByMaxDate(billCode).isEmpty()? "":instorageBillNewService.getReceiptDetailByMaxDate(billCode));
			json.put("instorageBill", instorageBillNewService.loadBillByCode(billCode));
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
			log.error("error",e);
		}
		out.print(json.toString());
	}
	/**
	 * 导向上架页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toInstorageUpPageNew/{billId}")
	public String toInstorageUpPageNew(@PathVariable("billId")Long billId,Model model) {
		try {
			InstorageBill  task=this.instorageBillNewService.loadById(billId);
		    model.addAttribute("task", task);
		} catch (Exception e) {
			
			log.error("error",e);
		}
		return "instorageNew/instorageBillUpNew";
	}
	/**
	 * 上架页面 根据LPN查询未上架信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "getUnUpAndUpDetailByLPN",method = RequestMethod.POST)
	public void getUnUpAndUpDetailByLPN(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String lpn=request.getParameter("lpn");
			String billCode=request.getParameter("billCode");
			List<ReceiptDetail> unUpReceiptDetailList=this.instorageBillNewService.getUnUpDetailByLPN(billCode,lpn);
			List<ReceiptDetail> upReceiptDetailList=this.instorageBillNewService.getUpDetailByLPN(billCode,lpn);
			json.put("status","success");
			json.put("unUpitems",unUpReceiptDetailList);
			json.put("upitems",upReceiptDetailList);

		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	@RequestMapping(value = "checkUpStorage",method = RequestMethod.POST)
	public void checkUpStorage(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String upStorage=request.getParameter("upStorage");
			List<CusStock> cusStockList=this.instorageBillNewService.checkUpStorage(upStorage);
			if(cusStockList.size()>0){
				json.put("status","error");
				json.put("content","库位存在,请重新输入!");
			}else{
				json.put("status","success");
			}
		
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	/**
	 * 上架
	 * @param taskCode
	 * @param response
	 */
	@RequestMapping(value = "upShelf",method = RequestMethod.POST)
	public void upShelf(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		String msg = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String upStorage=request.getParameter("upStorage");
			String lpn=request.getParameter("lpn");
			String sku=request.getParameter("sku");
			String batchCode = request.getParameter("batchCode");
			String productDate = request.getParameter("productDate");
			String expireDate = request.getParameter("expireDate");
			String num=request.getParameter("num");
			String billCode=request.getParameter("billCode");
			String errorFlag=request.getParameter("errorFlag");
			//上架
			msg = instorageBillNewService.finishUpShelf(billCode,lpn,sku, batchCode, productDate,
			    expireDate, upStorage,num,errorFlag);
		} catch(PaiUException ex){
            logger.error("error",ex);
            msg = "notMatch";
        } catch (Exception e) {
			logger.error("error.",e);
			msg = "false";
		}
		json.put("msg", msg);
		out.print(json.toString());
	}
	/**
	 * 关闭订单
	 */
	@RequestMapping(value = "close")
	public void close(@RequestParam("billId")Long billId,HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			response.setCharacterEncoding("utf-8");
			out = response.getWriter();
			json = new JSONObject();
			InstorageBill  bill=instorageBillNewService.loadById(billId);
			if(bill.getNewstatus().equals("3")||bill.getNewstatus().equals("6")){
				instorageBillNewService.sendQiMen(bill);
				json.put("status", "0");
				json.put("msg", "订单关闭成功!");
			}else{
				json.put("status", "1");
				json.put("msg", "不能关闭，不是完全上架!");
			}
		} catch (Exception e) {
			log.error("error",e);
			json.put("status", "-1");
			json.put("msg", "服务器异常");
		}
		out.print(json.toString());
	}
	/**
	 * 取消收货
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "cancalReceipt",method = RequestMethod.POST)
	public void cancalReceipt(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		String msg = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			Long id=Long.valueOf(request.getParameter("id"));
			//上架
			msg = instorageBillNewService.cancalReceipt(id);
			json.put("status", msg);
		} catch (Exception e) {
			logger.error("error.",e);
			msg = "false";
			json.put("content",e.getMessage());
			json.put("status", msg);
		}
		out.print(json.toString());
	}
	
	/**
	 * 根据LPN打印上架单
	 * @param lpn
	 * @param response
	 */
	@RequestMapping(value = "ajaxPrintLpnUpTask", method = RequestMethod.POST)
	public void printLpnUpTask(@RequestParam(value = "lpn") String lpn,@RequestParam(value = "billCode") String billCode, HttpServletResponse response){
		PrintWriter out = null;
		JSONObject json = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
//			json.put("content", instorageBillNewService.printLpnUpTask(lpn));
			json.put("instorageBillItemSJList",instorageScanService.getReceiptDetailSKUByLpn(lpn,billCode));
			json.put("receiptDate",instorageBillNewService.getReceiptDetailMaxDateByCodeAndLpn(billCode,lpn).isEmpty()? "":instorageBillNewService.getReceiptDetailMaxDateByCodeAndLpn(billCode,lpn));
			json.put("instorageBill", instorageBillNewService.loadBillByCode(billCode));
			json.put("status", "1");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			log.error("打印加载错误", e);
		}
	}
	
	/**
     * 查找sku批次信息
     * @param request
     * @param response
     */
    @RequestMapping(value = "findSku")
    public void findSku(ServletRequest request,HttpServletResponse response) {

        JSONObject json = null;
        PrintWriter out = null;
        try {
            json = new JSONObject();
            out = response.getWriter();
            
            //获取参数
            String billCode=request.getParameter("billCode");
            String sku=request.getParameter("sku");
            String customerCode=request.getParameter("customerCode");
            String lpnNo = request.getParameter("lpnNo");
            
            EdiGoodsSku ediGoodsSku = this.ediGoodsSkuService.findByCustomerCodeAndSku(customerCode, sku);
            //add LiBin bug617 防止界面输入的数据和数据库中存在大小写的区别
            if(ediGoodsSku == null || !ediGoodsSku.getSku().equals(sku)){
                json.put("status","skuNotExist");
                json.put("content","SKU不存在(查看大小写)!");
                logger.error("---------sku :"+sku+" not exist!-----");
            }else {
                json.put("status", "success");
                json.put("isBatchMgmt", ediGoodsSku.getIsBatchMgmt() == null ? "0" : ediGoodsSku.getIsBatchMgmt());
                json.put("isShelfLifeMgmt", ediGoodsSku.getIsShelfLifeMgmt() == null? "0" : ediGoodsSku.getIsShelfLifeMgmt());
                
                json.put("batchList",this.instorageBillNewService.batchList(billCode, lpnNo, sku));
                
            }
        } catch (Exception e) {
            json.put("status","error");
            json.put("content",e.getMessage());
            logger.error("error",e);
        }
        out.print(json.toString());
    }
	
}
